package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.HttpResponseException
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.SPUtil
import com.zhkj.txg.module.cart.entity.CartResponse
import com.zhkj.txg.module.home.entity.*
import com.zhkj.txg.module.home.model.HomeManager
import com.zhkj.txg.module.home.ui.BackTabEvent
import com.zhkj.txg.utils.ConfigManager
import io.reactivex.android.schedulers.AndroidSchedulers

class HomeViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager: HomeManager = HomeManager()
    private val backFragmentLiveData = MutableLiveData<BackTabEvent>()
    val homeDataLiveData = MutableLiveData<HttpResponse<HomeResponse>>()
    val shopListLiveData = MutableLiveData<HttpResponse<ShopListResponse>>()
    val hotGoodsLiveData = MutableLiveData<HttpResponse<HotGoodsResponse>>()
    val applyLiveData = MutableLiveData<HttpResponse<ApplyResponse>>()
    val tabIndexLiveData = MutableLiveData<Int>()
    val cartLiveData = MutableLiveData<HttpResponse<CartResponse>>()

    val updateLiveData = MutableLiveData<HttpResponse<VersionResponse>>()

    private val numb = 20
    var page = 1
        private set

    fun backFragmentSubscribe(): MutableLiveData<BackTabEvent> {
        val subscribe = RxBus.toObservable(BackTabEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread()).subscribe({
                backFragmentLiveData.value = it
            }, { it.printStackTrace() })
        dispose.add(subscribe)
        return backFragmentLiveData
    }

    fun getHomeData(map: Map<String, String>?) {
        val listener = object : ViewModelSubscribeListener<HomeResponse>(homeDataLiveData) {
            override fun onSuccess(resp: HomeResponse) {
                // 处理数据
//                val shopId = map?.get("shop_id") ?: "0"
//                resp.data.goods?.goods?.let {
//                    for (item in it) {
//                        item.shop_id = shopId
//                    }
//                }
                with(resp.data.sellData ?: SellDataEntity()) {
                    childNode.addAll(resp.data.sell)
                    resp.data.sellData = this
                }
                super.onSuccess(resp)
                page = 1
//                getHotGoods(token)
            }
        }
        val homeData = homeManager.homeData(map, listener)
        dispose.add(homeData)
//        return homeDataLiveData
    }

    fun getShopList(map: Map<String, String>?): MutableLiveData<HttpResponse<ShopListResponse>> {
        val listener = object : ViewModelSubscribeListener<ShopListResponse>(shopListLiveData) {
            override fun onSuccess(resp: ShopListResponse) {
                val map = hashMapOf<String, String>()
                resp.data?.get(0)?.id?.let {
                    map["shop_id"] = it
                    SPUtil.getInstance().putString(AccountManager.SHOP_ID, it)
                }
                getHomeData(map)
                super.onSuccess(resp)
            }
        }
        val shopList = homeManager.getShopList(map, listener)
        dispose.add(shopList)
        return shopListLiveData
    }

    /**
     * 获取热门商品数据
     */
    fun getHotGoods(
        token: String
    ) {
        val listener = object : ViewModelSubscribeListener<HotGoodsResponse>(hotGoodsLiveData) {
            override fun onSuccess(resp: HotGoodsResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        val hotGoods = homeManager.hotGoods(token, page, numb, listener)
        dispose.add(hotGoods)
    }

    /**
     * 获取配置
     */
    fun getConfig() {
        val listener = object : ViewModelSubscribeListener<ConfigResponse>(null) {
            override fun onSuccess(resp: ConfigResponse) {
                super.onSuccess(resp)
                ConfigManager.saveCustomerMobile(resp.data?.customerMobile ?: "")
                ConfigManager.saveProductShareContent(resp.data?.share?.productContent ?: "")
                ConfigManager.saveShareContent(resp.data?.share?.shareContent ?: "")
                ConfigManager.saveShareTitle(resp.data?.share?.shareTitle ?: "")
            }
        }
        val config = homeManager.config(listener)
        dispose.add(config)
    }

    /**
     * 获取服务端版本号
     */
    fun getVersion() {
        val listener = object : ViewModelSubscribeListener<VersionResponse>(updateLiveData) {
            override fun onSuccess(resp: VersionResponse) {
                super.onSuccess(resp)
            }
        }
        val config = homeManager.getVersion(listener)
        dispose.add(config)
    }

    fun isUserApply() {
        val apply = homeManager.isApply(AccountManager.getToken(), ViewModelSubscribeListener(applyLiveData))
        dispose.add(apply)
    }

    fun bindChatId(chatId: String) {
        val bindChatId = homeManager.bindChatId(AccountManager.getToken(), chatId, ViewModelSubscribeListener(null))
        dispose.add(bindChatId)
    }


    val addCartLiveData = MutableLiveData<HttpResponse<BaseResponse>>()

    /**
     * 添加购物车
     */
    fun addCart(map: Map<String, String>) {
        val listener = ViewModelSubscribeListener(addCartLiveData)
        val addCart = homeManager.addCart(map, listener)
        dispose.add(addCart)
    }

    /**
     * 获取购物车数据
     * */
    fun getCartNew(map: Map<String, String>) {
        val listener = object : ViewModelSubscribeListener<CartResponse>(cartLiveData) {
            override fun onSuccess(resp: CartResponse) {
                super.onSuccess(resp)
            }

            override fun onFailure(throwable: Throwable) {
                if (throwable is HttpResponseException && throwable.code == 401) RxBus.post(
                    BackTabEvent()
                )
                super.onFailure(throwable)
            }
        }
        val cart = homeManager.getCartNew(map, listener)
        dispose.add(cart)
    }


    val productListLiveData = MutableLiveData<HttpResponse<SearchProductResponse>>()
    fun searchProduct(
        token: String, shopId: Int, activeType: Int?, search: String?, catId: Int?, sort: String?,
        sortAsc: Boolean = false, recommend: Int?, restart: Boolean = false
    ) {
        val listener = object :
            ViewModelSubscribeListener<SearchProductResponse>(productListLiveData) {
            override fun onSuccess(resp: SearchProductResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        val searchProduct = homeManager.searchProduct(
            token, shopId, activeType, search, catId, sort,
            if (sortAsc) "asc" else "desc", page.toString(), numb.toString(), recommend, listener
        )
        dispose.add(searchProduct)
    }
}